<?php
class report extends baseobject
{
	public function __construct($params=array())
	{
		$this->aggregates=array();
		parent::init($params);
	}
	
	public function buildHeader() 
	{
		$header  = '<h1>' . $this->title . '</h1>';
		$header .= '<h2>' . $this->subtitle . '</h2>';
		$this->header=$header;
	}
	
	public function buildReport()
	{
		$this->buildHeader();
		$this->buildBody();
		$this->output = $this->header . $this->body . $this->footer;
	}
	
	public function buildBody()
	{
		$grandTotals = array();
		$res = mysql_query($this->sql);
		$numfields = mysql_num_fields($res) or die($this->sql . ' !!! ' . mysql_error());
		$numrows = mysql_num_rows($res);
		$body = "<div class='recordcount'>Found: $numrows records</div>" ;
		$body .= '<table border="0" class="report">';
		$body .= '<tr>';
		for($x=0; $x < $numfields; $x++) {
			$body .= '<th>' . mysql_field_name($res, $x) . '</th>';
		}
		$body .= '</tr>';
		while($row = mysql_fetch_row($res)) {
			$body .= '<tr>';
			for($x=0; $x < $numfields; $x++) {
				$body .= '<td>&nbsp;' . $row[$x] ;
				$fieldname = mysql_field_name($res,$x);
				if( in_array($fieldname, $this->aggregates) ) {
					$this->aggregate[$fieldname]+=(float) $row[$x];
					$grandTotals[$x] += (float) $row[$x];
				}
				$body.= '</td>';
			}
			$body.= '</tr>';
		}
		
		$body .= '<tr class="aggregates">';
		for($x=0; $x < $numfields; $x++) {
			$body .= '<th>&nbsp;' ;
			if( isset($grandTotals[$x]) ) $body.=number_format($grandTotals[$x],2);
			$body .= '</th>';
		}
		$body.='</tr>';
		$body .= '</table>';
		$this->body=$body;
	}
	
	public function show()
	{
		echo $this->output;
	}
	
	public function html()
	{
		return $this->output;
	}
}